package com.artifact.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.artifact.dao.GoodsInfoDao;
import com.artifact.model.GoodsInfo;

@Repository("goodsInfoDao")
public class GoodsInfoDaoImpl implements GoodsInfoDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public boolean addGoodsInfo(int goodsID, String goodsSName, int codeID, int codeLimitBuy, String goodsPic,
                                int isSale) {
        String sql = "INSERT INTO `goods_info` (`goodsID`, `goodsSName`, `codeID`, `codeLimitBuy`, `goodsPic`, `isSale`) VALUES (?,?,?,?,?,?)";
        return jdbcTemplate.update(sql, goodsID, goodsSName, codeID, codeLimitBuy, goodsPic, isSale) > 0;
    }

    @Override
    public GoodsInfo getGoodsInfo(int goodsID) {
        String sql = "SELECT * FROM goods_info where goodsID=?";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<GoodsInfo>(GoodsInfo.class), goodsID);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public GoodsInfo getGoodsInfo(String goodsSName, String goodsPic) {
        String sql = "SELECT * FROM goods_info where goodsSName=? and goodsPic = ?";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<GoodsInfo>(GoodsInfo.class), goodsSName, goodsPic);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public GoodsInfo getGoodsInfo(String goodsPic) {
        String sql = "SELECT * FROM goods_info where goodsPic = ?";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<GoodsInfo>(GoodsInfo.class), goodsPic);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public List<GoodsInfo> getGoodsInfos() {
        String sql = "SELECT * FROM goods_info";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<GoodsInfo>(GoodsInfo.class));
    }

    @Override
    public List<GoodsInfo> getGoodsInfosBySale() {
        String sql = "SELECT * FROM goods_info where isSale=1";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<GoodsInfo>(GoodsInfo.class));
    }

    @Override
    public void deleteGoodsInfo(int goodsID) {
        String sql = "DELETE FROM goods_info where goodsId=?";
        jdbcTemplate.update(sql, goodsID);
    }

    @Override
    public void setGoodsInfoIsSale(int goodsID, int isSale) {
        String sql = "UPDATE goods_info SET `isSale`=? WHERE `goodsID`=?";
        jdbcTemplate.update(sql, isSale, goodsID);
    }

}
